package com.jf.assistant;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


import com.jf.assistant.databinding.ActivitySettingBinding;
import com.jf.assistant.databinding.LyDialogsetappnameBinding;
import com.jf.bean.Action;
import com.jf.bean.AppInfo;
import com.jf.bean.AssistantTask;
import com.jf.controller.MainController;
import com.jf.viewadapter.ActionListAdapter;
import com.jf.viewadapter.ActionTaskListAdapter;
import com.kongzue.dialog.listener.InputDialogOkButtonClickListener;
import com.kongzue.dialog.v2.CustomDialog;
import com.kongzue.dialog.v2.InputDialog;


import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {


    public ActivitySettingBinding mainBinding;

    public ArrayList<Action> actions;
    public int position=-1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         mainBinding = ActivitySettingBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());

        Intent intent = this.getIntent();

        actions=(ArrayList<Action>)intent.getSerializableExtra("actions");
        // System.out.println(actions.size());

        try {

            if (actions!=null){

                Serializable position = intent.getSerializableExtra("position");
                this.position = (int) position;

                initRview();
                JfLog.logger(actions.size()+"");
            }else {
                actions= new ArrayList<Action>();
                initRview();
            }

        }catch (Exception e){
            JfLog.logger(e.toString());
            actions= new ArrayList<Action>();

        }

        initViewAction();
    }

    private void initViewAction() {
        mainBinding.btAddactionname.setOnClickListener(this);
        mainBinding.btAddactiontime.setOnClickListener(this);
        mainBinding.btEdaddopenapp.setOnClickListener(this);
        mainBinding.btAddactiondelay.setOnClickListener(this);
        mainBinding.btAddactionclicktext.setOnClickListener(this);
        mainBinding.btAddactionslidetext.setOnClickListener(this);
        mainBinding.btOnekeycreatejingdong.setOnClickListener(this);
    }


    RecyclerView recyclerView;
    ActionListAdapter actionTaskListAdapter;
    @SuppressLint("WrongConstant")
    public void initRview() throws ParseException {


        recyclerView = mainBinding.rlsettingactionlistview;
        if (recyclerView!=null){
            LinearLayoutManager layoutManager = new LinearLayoutManager(this );
//设置布局管理器
            recyclerView.setLayoutManager(layoutManager);
//设置为垂直布局，这也是默认的
            layoutManager.setOrientation(OrientationHelper. VERTICAL);
             actionTaskListAdapter = new ActionListAdapter(actions, this);
//        new NormalAdapter
//设置Adapter
            recyclerView.setAdapter(actionTaskListAdapter);
            //设置分隔线
            // recyclerView.addItemDecoration( new DividerGridItemDecoration(this ));
            //设置增加或删除条目的动画
            // recyclerView.setItemAnimator( new DefaultItemAnimator());
        }

        mainBinding.btActionsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AssistantTask assistantTask1 = new AssistantTask();
                for (Action action : actions){
                    if (action.getType()==Action.START_TIME){
                        assistantTask1.setStarttime(action.getStarttime());
                    }
                    if (action.getType()==Action.ACTIONNAME){
                        assistantTask1.setTaskname(action.getActionname());
                    }
                }
                assistantTask1.setActions(actions);
               // MainActivity.addAssistantTask(assistantTask1);
                try {

                    if (position!=-1){
                        MainController.saveAssistantTask(assistantTask1,SettingActivity.this,position);

                    }else {
                        MainController.saveAssistantTask(assistantTask1,SettingActivity.this);

                    }

                    finish();
                } catch (ParseException e) {
                    JfLog.logger("settingactivity储存task出错"+e.toString());
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onClick(View v) {

        if (v.getId()==mainBinding.btAddactionname.getId()){
            JfLog.logger("点击添加任务名称");

            InputDialog.show(this, "设置任务名称", "设置一个好听的名字吧", "确定", new InputDialogOkButtonClickListener() {
                @Override
                public void onClick(Dialog dialog, String inputText) {
                    Toast.makeText(SettingActivity.this, "您输入了：" + inputText, Toast.LENGTH_SHORT).show();
                    Action action = createAction(Action.ACTIONNAME, inputText, null);
                    actions.add(action);
                    dialog.dismiss();
                    actionTaskListAdapter.notifyDataSetChanged();

                }
            }, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

        }else if(v.getId()==mainBinding.btAddactiontime.getId()){
            JfLog.logger("点击添加任务时间");

            //添加任务时间弹窗
            CustomDialog.show(SettingActivity.this, R.layout.ly_dialogtimepick, new CustomDialog.BindView() {
                @Override
                public void onBind(final CustomDialog dialog, final View rootView) {
                    //绑定布局


                    final Button confirm=rootView.findViewById(R.id.bt_timepickconfirm);
                    Button cancel=rootView.findViewById(R.id.bt_timepickcancel);
//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                    confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失

                            TimePicker timepick=rootView.findViewById(R.id.timePicker);
                            timepick.getHour();
                            timepick.getMinute();
                            JfLog.logger(timepick.getHour()+":"+timepick.getMinute());
                            Action action = createAction(Action.START_TIME, timepick.getHour() + "", timepick.getMinute() + "");
                            actions.add(action);
                            actionTaskListAdapter.notifyDataSetChanged();
                            dialog.doDismiss();
                        }
                    });

                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失
                            // dialog.doDismiss();
                            dialog.doDismiss();
                        }
                    });

                }
            });

        }else if(v.getId()==mainBinding.btEdaddopenapp.getId()){
            JfLog.logger("点击添加打开任务app");

           // getInstallPackageName();
            //EditText med;
            CustomDialog.show(SettingActivity.this, R.layout.ly_dialogsetappname, new CustomDialog.BindView() {
                @Override
                public void onBind(final CustomDialog dialog, final View rootView) {
                    //绑定布局


                    final Button confirm=rootView.findViewById(R.id.bt_setappappnameconfirm);
                    Button cancel=rootView.findViewById(R.id.bt_setappnamecancel);
                    Button btisinstall=rootView.findViewById(R.id.bt_setappappnameisinstall);

                    btisinstall.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EditText med=rootView.findViewById(R.id.et_setappappname);
                            TextView tvpackagename=rootView.findViewById(R.id.tv_setappnamepackagename);
                            String installPackageName = getInstallPackageName(med.getText().toString().trim());
                            if (installPackageName!=null){
                                tvpackagename.setText("找到app,包名为："+installPackageName);

                            }else {
                                tvpackagename.setText("此app未安装，请确认是否安装当前app："+med.getText().toString());
                            }
                        }
                    });
//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                    confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失

                            EditText med=rootView.findViewById(R.id.et_setappappname);
                            TextView tvpackagename=rootView.findViewById(R.id.tv_setappnamepackagename);
                            String installPackageName = getInstallPackageName(med.getText().toString().trim());
                            if (installPackageName!=null){
                                Action action = createAction(Action.OPENAPP, med.getText().toString().trim(), installPackageName);
                                actions.add(action);
                                actionTaskListAdapter.notifyDataSetChanged();
                                dialog.doDismiss();
                            }else {
                                tvpackagename.setText("此app未安装，请确认是否安装当前app："+med.getText().toString());
                            }
                        }
                    });

                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失
                            // dialog.doDismiss();
                            dialog.doDismiss();
                        }
                    });

                }
            });




        }else if(v.getId()==mainBinding.btAddactiondelay.getId()){
            JfLog.logger("点击添加任务延迟时间");

            CustomDialog.show(SettingActivity.this, R.layout.ly_dialogdelaytime, new CustomDialog.BindView() {
                @Override
                public void onBind(final CustomDialog dialog, final View rootView) {
                    //绑定布局


                    final Button confirm=rootView.findViewById(R.id.bt_delaytimenameconfirm);
                    Button cancel=rootView.findViewById(R.id.bt_delaytimenamecancel);



//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                    confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失

                            EditText med=rootView.findViewById(R.id.et_delaytimetime);
                           String delaytime= med.getText().toString().trim();
                            if (!TextUtils.isEmpty(delaytime)){
                                Action action = createAction(Action.DELAY, delaytime, null);
                                actions.add(action);
                                actionTaskListAdapter.notifyDataSetChanged();
                                dialog.doDismiss();
                            }else {
                                Toast.makeText(SettingActivity.this,"请输入延迟时间，单位毫秒",Toast.LENGTH_SHORT).show();
                               // tvpackagename.setText("此app未安装，请确认是否安装当前app："+med.getText().toString());
                            }


                        }
                    });

                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失
                            // dialog.doDismiss();
                            dialog.doDismiss();
                        }
                    });

                }
            });






        }else if(v.getId()==mainBinding.btAddactionclicktext.getId()){
            JfLog.logger("点击添加任务点击文字");

            CustomDialog.show(SettingActivity.this, R.layout.ly_dialogsetclicktext, new CustomDialog.BindView() {
                @Override
                public void onBind(final CustomDialog dialog, final View rootView) {
                    //绑定布局


                    final Button confirm=rootView.findViewById(R.id.bt_clicktextconfirm);
                    Button cancel=rootView.findViewById(R.id.bt_clicktextcancel);



//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                    confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失

                            EditText med=rootView.findViewById(R.id.et_clicktext);
                            String clicktext= med.getText().toString().trim();
                            if (!TextUtils.isEmpty(clicktext)){
                                Action action = createAction(Action.CLICK, clicktext, null);
                                actions.add(action);
                                actionTaskListAdapter.notifyDataSetChanged();
                                dialog.doDismiss();
                            }else {
                                Toast.makeText(SettingActivity.this,"请输入点击文字",Toast.LENGTH_SHORT).show();
                                // tvpackagename.setText("此app未安装，请确认是否安装当前app："+med.getText().toString());
                            }


                        }
                    });

                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //Example：让对话框消失
                            // dialog.doDismiss();
                            dialog.doDismiss();
                        }
                    });

                }
            });

        }else if(v.getId()==mainBinding.btAddactionslidetext.getId()){
            JfLog.logger("点击添加任务点击文字");
            setSlidDialog();


        }else if (v.getId()==mainBinding.btOnekeycreatejingdong.getId()){
            JfLog.logger("一键创建密码");
                    setPassworkDialog();

        }


    }

    //创建滑动sliddialog
    private void setSlidDialog(){
        CustomDialog.show(SettingActivity.this, R.layout.ly_dialogsetslideposition, new CustomDialog.BindView() {
            @Override
            public void onBind(final CustomDialog dialog, final View rootView) {
                //绑定布局


                final Button confirm=rootView.findViewById(R.id.bt_slideconfirm);
                Button cancel=rootView.findViewById(R.id.bt_slidetextcancel);

//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Example：让对话框消失


                        EditText  etsx=rootView.findViewById(R.id.et_slidestartx);
                        EditText  etsy=rootView.findViewById(R.id.et_slidestarty);

                        EditText  etex=rootView.findViewById(R.id.et_slideendx);
                        EditText  etey=rootView.findViewById(R.id.et_slideendy);
                        String sx=etsx.getText().toString().trim();

                        if (!TextUtils.isEmpty(sx)){
                            String mstring=etsx.getText().toString().trim()+","+etsy.getText().toString().trim()+","+etex.getText().toString().trim()
                                    +","+etey.getText().toString().trim();
                            Action action = createAction(Action.SLIDE, mstring, null);
                            actions.add(action);
                            actionTaskListAdapter.notifyDataSetChanged();
                            dialog.doDismiss();
                        }else {
                            Toast.makeText(SettingActivity.this,"请输入点击文字",Toast.LENGTH_SHORT).show();
                            // tvpackagename.setText("此app未安装，请确认是否安装当前app："+med.getText().toString());
                        }


                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Example：让对话框消失
                        // dialog.doDismiss();
                        dialog.doDismiss();
                    }
                });

            }
        });
    }

    //设置passworddialog
    private void setPassworkDialog(){


        CustomDialog.show(SettingActivity.this, R.layout.ly_dialogsetopenpassword, new CustomDialog.BindView() {
            @Override
            public void onBind(final CustomDialog dialog, final View rootView) {
                //绑定布局


                final Button confirm=rootView.findViewById(R.id.bt_openphonepasswordconfirm);
                Button cancel=rootView.findViewById(R.id.bt_openphonepasswordcancel);

//                    ImageView btnOk = rootView.findViewById(R.id.btn_ok);
//                    //绑定事件
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Example：让对话框消失


                        EditText  etsx=rootView.findViewById(R.id.et_openphonepassword);

                        char[] chas=etsx.getText().toString().trim().toCharArray();


                        String mstring=200+","+600+","+200
                                +","+100;
                        //1.屏幕滑动
                        Action action = createAction(Action.SLIDE, mstring, null);
                        actions.add(action);

                        //2 延迟5秒
                        Action action2 = createAction(Action.DELAY, 5000+"", null);
                        actions.add(action2);

                        //3 循环创建点击密码事件
                        for (char cha: chas){
                            Action action3 = createAction(Action.CLICK, cha+"", null);
                            actions.add(action3);
                            //每次延迟5秒点击
                            Action action4 = createAction(Action.DELAY, 5000+"", null);
                            actions.add(action4);
                        }

                        actionTaskListAdapter.notifyDataSetChanged();
                        dialog.doDismiss();

                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Example：让对话框消失
                        // dialog.doDismiss();
                        dialog.doDismiss();
                    }
                });

            }
        });

    }

    public Action createAction( int actiontype,String actionvalue,String actionpackage) {
        //Log.e("jiafan",mDatas.get(position).getType()+"");
        Action newaction;
        switch (actiontype) {
            case Action.ACTIONNAME:
                newaction = new Action();
                newaction.setActionname(actionvalue);
                newaction.setType(Action.ACTIONNAME);
                return newaction;
                //break;
            case Action.START_TIME:
                newaction = new Action();
                Calendar actioncalendar1 = Calendar.getInstance();
                int hourofday = Integer.parseInt(actionvalue);
                int minute = Integer.parseInt(actionpackage);
                actioncalendar1.set(1990, 12, 1, hourofday, minute);
                newaction.setStarttime(actioncalendar1);
                newaction.setType(Action.START_TIME);
                return newaction;
           // break;
            case Action.OPENAPP:
                newaction = new Action();
                newaction.setOpenappname(actionvalue);
                newaction.setOpenapppackage(actionpackage);
                newaction.setType(Action.OPENAPP);
                return newaction;
           // break;
            case Action.DELAY:
                newaction = new Action();
                int delaytim = Integer.parseInt(actionvalue);
                newaction.setDelaytime(delaytim);
                newaction.setType(Action.DELAY);
                return newaction;
           // break;
            case Action.CLICK:

                newaction = new Action();
                newaction.setClicktext(actionvalue);
                newaction.setType(Action.CLICK);

                return newaction;

            case Action.SLIDE:

                newaction = new Action();
                newaction.setSlidestartend(actionvalue);
                newaction.setType(Action.SLIDE);

                return newaction;
           // break;
            };
            return null;
        }



        public String getInstallPackageName(String appname){
            PackageManager pm = getPackageManager();
            List<PackageInfo> installedPackages = pm.getInstalledPackages(0);  // 获取所以已安装的包
            ArrayList<HashMap<String, Object>> listItems = new ArrayList<HashMap<String, Object>>();
            ArrayList<AppInfo> list = new ArrayList<AppInfo>();
            for (PackageInfo packageInfo : installedPackages) {

                String packageName = packageInfo.packageName;  // 包名
                ApplicationInfo applicationInfo = packageInfo.applicationInfo;  // 应用信息
                String name = applicationInfo.loadLabel(pm).toString();  // 应用名称
                Drawable icon = applicationInfo.loadIcon(pm);  // 应用图标
               if(name.equals(appname)){

                   return packageName;
               }else {

                  // return null;
               }


            }
            return null;

        }


    }
